#!/bin/sh

if [ $# -lt 1 ]
then
	echo "usage: $0 'srm-path' ";
	exit 1;
fi


findfiles()
{
#	local path2=`srmls "$1"  | awk ' {if (NR!=1 && NF==2) print $2; if (NR!=1 && NF>2) print $4 }' | sed -e  's/\(.*\)\/\(.*\)\//\2\//'`;
#	echo "path2: $path2"
#	local path=`echo "$path2" |  sed -e  's/\(.*\)\/\(.*\)/\2/'` 

	local path=`lcg-ls $1 |  sed -e  's/\(.*\)\/\(.*\)/\2/'` 
#	echo "path: $path"

	for name in ${path[@]}
		do
#			local y=\$$2
			local file=`echo $name |  awk '{if (match($0,"root") ) print $0 }'`
#			local file=`echo $name |  awk '{if (match($0,".") ) print $0 }'`
#			echo "file: $file"
			if [ -n "$file"  ]
			then
				echo "srmrm \"$1/$name\" ";
			else
				findfiles "$1/$name/";
			fi
		done
			echo "srmrmdir \"$1\" ";

}

delfiles()
{
#	 local path2=`srmls "$1"  | awk ' {if (NR!=1 && NF==2) print $2; if (NR!=1 && NF>2) print $4 }' | sed -e  's/\(.*\)\/\(.*\)\//\2\//'`;
#        local path=`echo "$path2" |  sed -e  's/\(.*\)\/\(.*\)/\2/'`
	local path=`lcg-ls $1 |  sed -e  's/\(.*\)\/\(.*\)/\2/'`
	for name in ${path[@]}
		do
#			local y=\$$2
			local file=`echo $name |  awk '{if (match($0,"root") ) print $0 }'`
#			local file=`echo $name |  awk '{if (match($0,".") ) print $0 }'`
			if [ -n "$file"  ]
			then
				echo "srmrm -debug  \"$1/$name\" " | sh;
			else
				delfiles "$1/$name/";
			fi
		done
			echo "srmrmdir -debug \"$1\" " | sh;

}


findfiles $1


echo -n "Are you ready to delete the files/directories above? [y/n] ";
read x

if [ "$x"  = 'y' ]
then
	delfiles $1
fi
